package com.legsem.legstar.cci;

import javax.resource.ResourceException;
import javax.resource.cci.LocalTransaction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.legsem.legstar.jca.LegStarManagedConnection;
import com.legstar.messaging.RequestException;

/**
 * Perform commit and rollback for 1PC.
 * <p/>
 * As per the JCA contract, notifies the application server of local transaction
 * related events.
 * 
 */
public class LegStarLocalTransactionImpl implements LocalTransaction {

    /** Logger. */
    private final Log log = LogFactory.getLog(getClass());

    private LegStarManagedConnection managedConnection;

    public LegStarLocalTransactionImpl(
            LegStarManagedConnection managedConnection) {
        this.managedConnection = managedConnection;
    }

    /**
     * Transaction start is implicit on the mainframe.
     * */
    public void begin() throws ResourceException {
        if (log.isDebugEnabled()) {
            log.debug("Transaction begin requested");
        }
        managedConnection.transactionStarted();

    }

    public void commit() throws ResourceException {
        try {
            if (log.isDebugEnabled()) {
                log.debug("Transaction commit requested");
            }
            managedConnection.getHostConnection().commitUOW();
            managedConnection.transactionCompleted();
        } catch (RequestException e) {
            throw new ResourceException(e);
        }

    }

    public void rollback() throws ResourceException {
        try {
            if (log.isDebugEnabled()) {
                log.debug("Transaction rollback requested");
            }
            managedConnection.getHostConnection().rollbackUOW();
            managedConnection.transactionRolledback();
        } catch (RequestException e) {
            throw new ResourceException(e);
        }
    }

}
